'use strict';

/**
 * 订单
 * OrderController
 * @constructor
 */

App.controller('OrderController', function($rootScope, $scope, $http, $stateParams, ngDialog) {
	
	
	//立即下单（此时后台并不会创建订单）
	$scope.preOrder = function() {
        $http.get('Order/preOrder/'+ $stateParams.goodsId + '.json').success(function(order){
            $scope.order = order;
            console.log(order);
        }).error(function(data, status, headers, config) {
           // $scope.setError('Error 系统错误 ：'+data);
            showError(msg);
        });
    };
    $scope.preOrder();
    
    $scope.showError = function(msg) {
	   var alertPopup = $ionicPopup.alert({
	     title: '错误信息：',
	     template: msg
	   });
	   alertPopup.then(function(res) {
	     console.log('Thank you for not eating my delicious ice cream cone');
	   });
	};

	//用户下单，后台创建订单，并查询订单详情。
	$scope.submitOrder = function(order) {
		console.log(order);
		$http.post('Order/createOrder', order).success(function() {
            console.log("创建订单成功:￥"+order.realMoney);
        }).error(function(apiErrorInfo, status, headers, config) {
        	
            $scope.setError("错误代码："+apiErrorInfo.errcode+" 错误描述："+apiErrorInfo.errmsg);
            alert(apiErrorInfo.errmsg);
        });
    };
    
    //商品数量 +1
    $scope.add = function(goodsDetail){
    	
    	goodsDetail.goodsNumber = goodsDetail.goodsNumber + 1;
    	goodsDetail.total = goodsDetail.goodsNumber * goodsDetail.realPrice;
    	$scope.order.realMoney = $scope.order.realMoney + goodsDetail.realPrice;
    	
    }
    
    //商品数量 -1
    $scope.plus = function(goodsDetail){
    	if(goodsDetail.goodsNumber>1){
	    	goodsDetail.goodsNumber = goodsDetail.goodsNumber - 1;
	    	goodsDetail.total = goodsDetail.goodsNumber * goodsDetail.realPrice;
	    	$scope.order.realMoney = $scope.order.realMoney - goodsDetail.realPrice;
    	}
    }
    
    $scope.choiseAddress = function(){
    	ngDialog.open({ template: 'addressListDialog'});
    }
    
    $scope.setError = function(message) {
        $scope.error = true;
        $scope.errorMessage = message;
    };

    $rootScope.$on('ngDialog.templateLoading', function (e, template) {
    	console.log('ngDialog template is loading: ' + template);
    });
    
    $rootScope.$on('ngDialog.templateLoaded', function (e, template) {
    	console.log('ngDialog template loaded: ' + template);
    });
    
    $rootScope.$on('ngDialog.opened', function (e, $dialog) {
        console.log('ngDialog opened: ' + $dialog.attr('id'));
    });

    $rootScope.$on('ngDialog.closed', function (e, $dialog) {
        console.log('ngDialog closed: ' + $dialog.attr('id'));
    });

    $rootScope.$on('ngDialog.closing', function (e, $dialog) {
        console.log('ngDialog closing: ' + $dialog.attr('id'));
    });

});





